package com.yb.guigu.pick.core.util;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/20 14:41
 * FileName: StreamUtil
 * Description:
 */
@Slf4j
public class StreamUtil {
    public static final <T> T readAsObject(Class<T> tClass, InputStream servletInputStream){
        try {
            byte[] bs= new byte[servletInputStream.available()];
            int len=-1;
            StringBuilder sb=new StringBuilder();
            while((len=servletInputStream.read(bs))>0){
                sb.append(new String(bs,0,len));
            }
            String s = sb.toString();
            return JSONObject.parseObject(s,tClass);
        } catch (IOException e) {
            log.error("StreamUtil readAsObject error:{}",e);
        }
        return null;
    }

    public static final String readAsString(InputStream servletInputStream){
        try {
            byte[] bs= new byte[servletInputStream.available()];
            servletInputStream.read(bs);
            return new String(bs);
        } catch (IOException e) {
            log.error("StreamUtil readAsString error:{}",e);
        }
        return "";
    }

}
